import SendMsg from "@/api/SendMsg";
import {message} from "ant-design-vue";
import i18n from "../../../i18n/index";

const JsRunLot = {
    namespaced: true,
    state: {
        // table数据
        dataSource: [],
        waferDataSource: [],
        waferMapDataSource: [],
        waferDefeDataSource: [],
        waferSiteDataSource: [],
        defeDetailDataSource:[],
        siteId : '',
        waferSiteForm:{
            front: '',
            edge: '',
            backside : '',
            aqlStandard : '',
            acceptHold: '',
            aqlResult : '',
            defeCnt: '',
        },
        // 查询条件
        mapData:{},
        queryForm: {
           type: undefined,
           lotId: '',
           state: 'non-Hold',
        },
        typeList:[
            { value: 'WAT', lable: 'WAT' },
            { value: 'CP' , lable: 'CP'},
            { value: 'other' , lable: 'other'}
        ],
        loadTable: false,
        runLotsMapModalVisible: false,
        runLotsDefeModalVisible: false,
        runLotsDefeDetailModalVisible: false,
        aqlStandard: '',
        chooseWaferId: '',
        acceptHold: '',
        dataPagination: {
            current: 1,
            pageSize: 14,
            total: 0,
            showTotal: (total, range) => {
                return i18n.t('menuItem.total')+` ${total} `+i18n.t('menuItem.term')
            },
        },
        defeDetailPagination: {
            current: 1,
            pageSize: 10,
            total: 0,
            size:"small",
            onChange: (current) => {
                JsRunLot.state.defeDetailPagination.current = current
            },
            showTotal: (total, range) => {
                return i18n.t('menuItem.total')+` ${total} `+i18n.t('menuItem.term')
            },
        },
        lotDefeForm: {
            lotId: '',
            productId: '',
            quantity: '',
            comment: ''
        },
        lotMapForm:{
            lotId: '',
            inspectionDie: '',
            grossDie: '',
        },
        dieLayerList : [],
        dieCodeList : [],
        lotDefeClickWaferId : '',
        lotDefeClickSiteId : '',
        loading:false,
        // table选中行
        rowSelection: {
            selectedRowKeys: [],
            type: 'radio',
            onChange: (selectedRowKeys, selectedRows) => {
                JsRunLot.state.rowSelection.selectedRowKeys = selectedRowKeys;
            },
        },
        selectAllWafer: false,
        butLoading: false,
        clickLotId: '',
    },
    mutations: {
        //查询table
        queryLot(state) {


            let inTrx = {
                trxId: "runingLot",
                actionFlg: "Q",
                pageSize: state.dataPagination.pageSize,
                pageNum: state.dataPagination.current,
                ...state.queryForm
            };
            state.dataSource = []
            state.loadTable = true
            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    if(outTrx.runIngLotOAList){
                        state.dataSource = outTrx.runIngLotOAList.map((item, index) => {
                            item.key = (index + 1);
                            return item;
                        });
                    }
                }
                state.dataPagination.total = outTrx.tblCnt;
            }).finally(() => {
                state.waferDataSource = []
                state.loadTable = false
            });
        },
        //初始化
        initLot(state) {
            let inTrx = {
                trxId: "runingLot",
                actionFlg: "Q",
                pageSize: state.dataPagination.pageSize,
                pageNum: state.dataPagination.current,
                ...state.queryForm
            };
            state.dataSource = []
            state.loadTable = true
            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    if(outTrx.runIngLotOAList){
                        state.dataSource = outTrx.runIngLotOAList.map((item, index) => {
                            item.key = (index + 1);
                            return item;
                        });
                    }
                }
                state.dataPagination.total = outTrx.tblCnt;
            }).finally(() => {
                state.loadTable = false
            });
        },

        setDataPagination(state, val) {
            state.dataPagination = val;
        },
        //查询prodId相关数据
        queryProductInfo(state){
            let intrx = {
                trxId: "productConfig",
                actionFlg: "QPC",
                productName: state.lotDefeForm.productId,
            };
            SendMsg.sendPostTrx(intrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.mapData = {}
                    if(outTrx.oaryC){
                        state.mapData = outTrx.oaryC
                    }
                }
            })
        },

        clickCell(state, record){
            state.selectRow = record
            let inTrx = {
                trxId: "runingLot",
                actionFlg: "MAPQ",
                lotId: state.selectRow.lotId
            };

            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    if(outTrx.runIngLotOBList){
                        state.waferDataSource = outTrx.runIngLotOBList.map((item, index) => {
                            item.key = (index + 1);
                            return item;
                        });
                    }
                    state.lotMapForm.lotId = state.selectRow.lotId
                    state.lotMapForm.inspectionDie = outTrx.inspectionDie
                    state.lotMapForm.grossDie = outTrx.grossDie
                }
            }).finally(() => {

            });
            state.runLotsMapModalVisible = true
        },
        queryWaferTableData(state,val){
            let inTrx = {
                trxId: "runingLot",
                actionFlg: "MAPQ",
                lotId: val
            };

            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    if(outTrx.runIngLotOBList){
                        state.waferDataSource = outTrx.runIngLotOBList.map((item, index) => {
                            item.key = (index + 1);
                            return item;
                        });
                    }
                    state.lotMapForm.lotId = state.selectRow.lotId
                    state.lotMapForm.inspectionDie = outTrx.inspectionDie
                    state.lotMapForm.grossDie = outTrx.grossDie
                    state.clickLotId = val
                }
            }).finally(() => {

            });
        },
        modalConfirm(state){
            let inTrx = {
                trxId: "runingLot",
                actionFlg: "QWAFER",
                lotId: state.lotMapForm.lotId
            };
            state.waferDefeDataSource = []
            state.loading = true
            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {

                    if(outTrx.runIngLotOBList){
                        state.waferDefeDataSource = outTrx.runIngLotOBList.map((item, index) => {
                            item.key = (index + 1);
                            return item;
                        });
                        state.lotDefeForm.lotId = state.lotMapForm.lotId
                        state.lotDefeForm.productId = state.selectRow.productName
                        state.lotDefeForm.quantity = state.selectRow.quantity
                        state.lotDefeForm.comment = outTrx.comment
                        state.aqlStandard = outTrx.aqlStandard
                        state.acceptHold = outTrx.acceptHold
                        state.waferSiteForm.aqlStandard = state.aqlStandard
                        state.waferSiteForm.acceptHold = state.acceptHold
                        state.runLotsMapModalVisible = false
                        state.selectAllWafer = false
                        state.runLotsDefeModalVisible = true
                        JsRunLot.mutations.queryProductInfo(state)
                    }
                }
            }).finally(() => {
                state.loading = false
                JsRunLot.mutations.setButtonColor(state)
            });


        },
        //serial有值时，说明选择了wafer，选择的wafer用淡蓝色突出
        setButtonColor(state, serial){

            for (let i = 0; i < 25; i++){
                let waferNo = '01';
                if(i<9){
                    waferNo = 'W' + '0' + (i+1)
                }else {
                    waferNo = 'W' + (i+1)
                }

                let wafer = state.waferDefeDataSource.filter(e => e.waferNo == (i+1))[0]

                //取位置
                let myButton = document.getElementById( waferNo)
                if(!myButton){
                    continue
                }
                if(!wafer || !wafer.waferId || wafer.waferId.indexOf('#') === -1){
                    myButton.disabled = true
                    myButton.style.background = '#f5f5f5'
                    continue
                }
                if (serial && waferNo === 'W' + serial){
                    myButton.disabled = false
                    myButton.style.background = '#aee8ff'
                    continue
                }

                //取判定结果，不存在NG
                let judgeResult = wafer.judgeResult;
                if (judgeResult === '2') {
                    myButton.disabled = false
                    myButton.style.background = 'green'
                } else if (judgeResult === '1') {
                    myButton.disabled = false
                    myButton.style.background = '#1c94fc'
                } else if (judgeResult === '0') {
                    myButton.disabled = false
                    myButton.style.background = 'red'
                } else {
                    myButton.disabled = true
                }
            }
        },

        clickWafer(state,val){
            //取消全选选择框
            state.selectAllWafer = false
            //更新选中颜色
            JsRunLot.mutations.setButtonColor(state, val)
            let wafer = state.waferDefeDataSource.filter(e => e.waferNo === val)[0]
            state.lotDefeClickWaferId = wafer.waferId
            state.chooseWaferId = wafer.waferId
            let inTrx = {
                trxId: "runingLot",
                actionFlg: "QSITE",
                waferId: state.lotDefeClickWaferId
            };
            state.waferSiteDataSource = [];
            state.loadTable = true
            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    if(outTrx.runIngLotOCList){
                        state.waferSiteDataSource = outTrx.runIngLotOCList.map((item, index) => {
                            item.key = 'S' + (index + 1);
                            return item;
                        });
                        state.waferSiteForm = state.waferSiteDataSource[0]
                        state.waferSiteForm.aqlStandard = state.aqlStandard
                        state.waferSiteForm.acceptHold = state.acceptHold
                        state.waferSiteForm.defeCnt = outTrx.defeCnt
                    }else {
                        for(let i=0; i<9; i++){
                            let defe = {};
                            defe.key = 'S' + (i + 1);
                            defe.waferId = state.lotDefeClickWaferId
                            defe.site = defe.key
                            defe.siteJudge = '1';
                            defe.aqlStandard = state.aqlStandard
                            defe.acceptHold = state.acceptHold
                            state.waferSiteDataSource = [...state.waferSiteDataSource,defe]
                        }
                        state.waferSiteForm = state.waferSiteDataSource[0]
                        state.waferSiteForm.aqlStandard = state.aqlStandard
                        state.waferSiteForm.acceptHold = state.acceptHold
                    }
                    console.log(state.waferSiteDataSource,"state.waferSiteDataSource")
                    state.loadTable = false
                }
            }).finally(() => {

            });
        },

        addDetail(state){
            let defeDetail
            if(state.defeDetailDataSource.length){
                 defeDetail = {
                     key: state.defeDetailDataSource.length + 1,
                     waferId : state.lotDefeClickWaferId,
                     site : state.lotDefeClickSiteId,
                }
            }else {
                 defeDetail = {
                     key: 1,
                     waferId : state.lotDefeClickWaferId,
                     site : state.lotDefeClickSiteId,
                }
            }

            state.defeDetailDataSource = [...state.defeDetailDataSource, defeDetail]

        },

        copyDefe(state,val){
            let defeDetail = {...val}
            defeDetail.key = state.defeDetailDataSource.length + 1
            defeDetail.badDefectFlag = null
            state.defeDetailDataSource = [...state.defeDetailDataSource, defeDetail]

        },
        deleteDefe(state, val){
            state.defeDetailDataSource = state.defeDetailDataSource.filter(item=> item.key != val.key)
            state.defeDetailDataSource = state.defeDetailDataSource.map((item, index) =>{
                item.key = (index +1);
                return item
            })
            if(state.rowSelection.selectedRowKeys && state.rowSelection.selectedRowKeys[0] === val.key){
                state.rowSelection.selectedRowKeys = []
            }
        },

        DieDefeDetailButton(state,val){
            state.lotDefeClickWaferId = val.waferId
            state.lotDefeClickSiteId = val.site
            if(!val.siteJudge || val.siteJudge == 1){
                message.warn(i18n.t('menuItem.dieNGPlaceholder'));
                return;
            }
            state.siteId = val.site;
            let inTrx = {
                trxId: "runingLot",
                actionFlg: "QDIE",
                waferId: val.waferId,
                siteId : val.site
            };
            state.defeDetailDataSource = [];
            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    if(outTrx.runIngLotODList){
                        state.defeDetailDataSource = outTrx.runIngLotODList.map((item, index) => {
                            item.key = (index + 1);
                            if(item.badDefectFlag && item.badDefectFlag === 'Y'){
                                state.rowSelection.selectedRowKeys.push(item.key)
                            }
                            return item;
                        });
                    }
                }
            }).finally(() => {
                state.runLotsDefeDetailModalVisible = true
            });
        },
        defeModalDetailCancel(state){
            state.runLotsDefeDetailModalVisible = false
            JsRunLot.mutations.cleanDefeDetail(state)
        },
        defeModalDetailConfirm(state){
            let inTrx = {
                trxId: "runingLot",
                actionFlg: "DEDECO",
                waferId: state.lotDefeClickWaferId,
                siteId : state.lotDefeClickSiteId,
                runIngLotIDList: state.defeDetailDataSource
            };
            let cnt = state.defeDetailDataSource ? state.defeDetailDataSource.length:0

            if(state.defeDetailDataSource.length != 0){
                if( !state.rowSelection.selectedRowKeys[0]){
                    message.warn(i18n.t('menuItem.diePlaceholder'));
                    return;
                }
            }

            if(state.defeDetailDataSource.length != 0){
                let dieArr = [];
                let badDefeDetail = state.rowSelection.selectedRowKeys[0];
                for(let i=0; i<state.defeDetailDataSource.length;i++){
                    let defeDetail = state.defeDetailDataSource[i]
                    let dieNo = defeDetail.dieNo
                    let siteLayer = defeDetail.dieLayer
                    let dieCode = defeDetail.dieCode
                    if(!dieNo ){
                        message.warn(i18n.t('menuItem.dieNoIsNotNull'))
                        return;
                    }
                    if(dieNo.length > 100){
                        message.warn(i18n.t('menuItem.dieLengthWarn')+ dieNo);
                        return
                    }
                    if(dieArr.indexOf(dieNo) != -1){
                        message.warn(i18n.t('menuItem.dieNoDuplicate') + dieNo);
                        return;
                    }
                    if(!siteLayer || !dieCode){
                        message.warn(i18n.t('menuItem.layerCodeIsNotNull') + dieNo);
                        return;
                    }
                    if(badDefeDetail === defeDetail.key){
                        state.defeDetailDataSource[i].badDefectFlag = 'Y'
                    }else {
                        state.defeDetailDataSource[i].badDefectFlag = null
                    }
                    dieArr.push(dieNo)
                }
            }


            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    message.success(i18n.t('success'))
                    let inTrx = {
                        trxId: "runingLot",
                        actionFlg: "QSITE",
                        waferId: state.lotDefeClickWaferId
                    };
                    state.waferSiteDataSource = [];
                    state.loadTable = true
                    SendMsg.sendPostTrx(inTrx).then((res) => {
                        let outTrx = res.data;
                        if ('0000000' === outTrx.rtnCode) {
                            if(outTrx.runIngLotOCList){
                                state.waferSiteDataSource = outTrx.runIngLotOCList.map((item, index) => {
                                    item.key = 'S' + (index + 1);
                                    return item;
                                });
                                state.waferSiteForm = state.waferSiteDataSource[0]
                                state.waferSiteForm.aqlStandard = state.aqlStandard
                                state.waferSiteForm.acceptHold = state.acceptHold
                            }
                            state.waferSiteForm.defeCnt = outTrx.defeCnt
                            state.loadTable = false
                        }
                    }).finally(() => {

                    });
                    JsRunLot.mutations.cleanDefeDetail(state)
                    state.runLotsDefeDetailModalVisible = false
                    //判定结束 更新颜色
                    JsRunLot.mutations.updateButtonColor(state)
                }
            }).finally(() => {

            });
        },
        //更新颜色
        updateButtonColor(state){
            let inTrx = {
                trxId: "runingLot",
                actionFlg: "QWAFER",
                lotId: state.lotMapForm.lotId
            };
            state.waferDefeDataSource = []
            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    if (outTrx.runIngLotOBList) {
                        state.waferDefeDataSource = outTrx.runIngLotOBList.map((item, index) => {
                            item.key = (index + 1);
                            return item;
                        });
                    }
                    let slot = state.chooseWaferId.split("#")[1];
                    let waferNo = 'W' + slot;
                    // //取位置
                    let myButton = document.getElementById(waferNo)
                    let wafer = state.waferDefeDataSource.filter(e => e.waferId === state.chooseWaferId)[0]
                    if (!wafer || !wafer.waferId || wafer.waferId.indexOf('#') === -1) {
                        myButton.disabled = true
                        myButton.style.background = '#f5f5f5'
                        return
                    }
                    //取判定结果，不存在NG
                    let judgeResult = wafer.judgeResult;
                    if (judgeResult === '2') {
                        myButton.disabled = false
                        myButton.style.background = 'green'
                    } else if (judgeResult === '1') {
                        myButton.disabled = false
                        myButton.style.background = '#1c94fc'
                    } else if (judgeResult === '0') {
                        myButton.disabled = false
                        myButton.style.background = 'red'
                    } else {
                        myButton.disabled = true
                    }
                }
            });
        },
        waferSubmit(state){
            let waferId
            //选择了全选复选，如果wafer已经做过判断就报错
            if (state.selectAllWafer){
                let isJudgeWaferList = state.waferDefeDataSource.filter(e => e.retWaferJudgeOVList).map(i => i.waferId)
                if (isJudgeWaferList.length > 0){
                    message.warn(i18n.t('waferIsJudge', {waferList: isJudgeWaferList}))
                    return
                }
                waferId = state.waferDefeDataSource.map(i => i.waferId).join(',')
            }else{
                if(!state.lotDefeClickWaferId){
                    message.warn(i18n.t('menuItem.waferIdNotNull'))
                    return
                }
                waferId = state.lotDefeClickWaferId
            }

            let inTrx = {
                trxId: "runingLot",
                actionFlg: "WAC",
                waferId: waferId,
                lotId :state.lotMapForm.lotId,
                aqlStandard: state.waferSiteForm.aqlStandard,
                acceptHold: state.waferSiteForm.acceptHold,
                front: state.waferSiteForm.front,
                edge: state.waferSiteForm.edge,
                backside: state.waferSiteForm.backside,
                defeCnt: state.waferSiteForm.defeCnt
            };
            state.butLoading = true
            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    message.success(i18n.t('success'))
                    //刷新table JudgeFlg,返回成功 则JudgeFlg = Y
                    if (outTrx.judgeFlg === 'Y'){
                        state.dataSource.filter(e => e.lotId === state.lotMapForm.lotId)[0].judgeFlg = "Y"
                    }
                }
            }).finally(() => {
                state.butLoading = false
                if (state.lotDefeClickWaferId){
                    JsRunLot.mutations.clickWafer(state, state.lotDefeClickWaferId.split("#")[1])
                }
                JsRunLot.mutations.modalConfirm(state)
            });
        },
        lotSubmit(state){

            let inTrx = {
                trxId: "runingLot",
                actionFlg: "LOTC",
                lotId :state.lotMapForm.lotId,
            };
            SendMsg.sendPostTrx(inTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    JsRunLot.mutations.cleanAll(state)
                    JsRunLot.mutations.initLot(state)
                    message.success(i18n.t('success'))
                    state.runLotsDefeModalVisible = false
                }

            }).finally(() => {
            });
        },

        defeModalCancel(state){
            JsRunLot.mutations.cleanDefe(state)
            state.runLotsDefeModalVisible = false
        },

        modalCancel(state){
            state.runLotsMapModalVisible = false
        },
        initDieLayerData(state){
            let inTrx = {
                trxId: "bisData",
                actionFlg: "Q",
                iary: [{
                    dataCate: 'LAER',
                }]
            };
            SendMsg.sendPostTrx(inTrx).then(res => {
                if (res.data.rtnCode !== '0000000') {
                    return
                }
                state.dieLayerList = res.data.oary.map(e => {
                    return {
                        label: e.dataDesc,
                        value: e.dataId,
                    }
                });
            });
        },
        initDieCodeData(state){
            let inTrx = {
                trxId: "bisData",
                actionFlg: "Q",
                iary: [{
                    dataCate: 'LYDE',
                }]
            };
            SendMsg.sendPostTrx(inTrx).then(res => {
                if (res.data.rtnCode !== '0000000') {
                    return
                }
                state.dieCodeList = res.data.oary.map(e => {
                    return {
                        label: e.dataDesc,
                        value: e.dataId,
                    }
                });
            });
        },
        // 清空弹窗数据
        cleanAll(state) {
            state.dataSource = [],
            state.waferDataSource = [],
            state.queryForm = {
                type: '',
                lotId: '',
            },
            state.dataPagination = {
                current: 1,
                    pageSize: 14,
                    total: 0,
                    showTotal: (total, range) => {
                        return i18n.t('menuItem.total')+` ${total} `+i18n.t('menuItem.term')
                },
            },
            state.lotMapForm={
                inspectionDie: '',
                grossDie: '',
                lotId: '',
            }
            state.chooseWaferId = '',
            state.mapData = {}
        },
        cleanDefe(state) {
            state.lotDefeForm = {
                lotId: '',
                productId: '',
                quantity: '',
                comment: ''
            }
            state.waferDefeDataSource = []
            state.waferSiteDataSource = []
            state.aqlStandard = ''
            state.acceptHold = ''
            state.lotDefeClickWaferId = '',
            state.lotDefeClickSiteId = '',
            state.waferSiteForm={
                front: '',
                    edge: '',
                    backside : '',
                    aqlStandard : '',
                    acceptHold: '',
                    aqlResult : '',
                    defeCnt: '',
            },
            state.lotMapForm={
                inspectionDie: '',
                grossDie: '',
                lotId: '',
            }
            state.chooseWaferId = '',
            state.mapData = {}
        },
        cleanDefeDetail(state){
            state.lotDefeClickSiteId = '';
            state.defeDetailDataSource = [];
            state.rowSelection.selectedRowKeys = [];
        },
        clickAll(state){
            state.selectAllWafer = !state.selectAllWafer
        }
    },
    getters: {},
    action: {}
}
export default JsRunLot;
